<template>
	<div class="mine-apply-agent-wrap">
		<van-nav-bar :title="title" left-arrow fixed @click-left="onClickLeft" />
		<!-- <img class="bg-img" src="../../../images/mine/mine-apply-agent-bg.png"> -->

		<div class="form-wrap">

			<van-form @submit="onSubmit" error-message-align="right" input-align="right">
				<!-- @click="msg==1?false:showPopuplevel = true" :is-link="msg==0" -->
				<van-field v-model="level_name" readonly name="level" label="申请代理级别：" placeholder="请选择申请代理级别"
					:rules="[{ required: true, message: '请选择申请代理级别' }]" />
				<van-field v-if="level == 0 || level == 100" v-model="region_name" name="region_name" label="代理区域"
					placeholder="请选择代理区域" :rules="[{ required: true, message: '请选择代理区域' }]" @click="bigShowPopup = true"
					readonly is-link />
				<van-field v-else v-model="region_name" name="region_name" label="代理区域：" placeholder="请选择代理区域"
					:rules="[{ required: true, message: '请选择代理区域' }]" @click="showPopup = true" readonly is-link />
				<!--  bigAgentConfig-->
				<!-- <van-field v-if="level == 0" v-model="name" name="name" label="姓名：" placeholder="请输入姓名"
					:rules="[{ required: true, message: '请输入姓名' }]" /> -->
				<van-field v-model="company_name" type="text" name="company_name" label="公司名称：" placeholder="请输入公司名称"
					:rules="[{ required: true, message: '请输入公司名称' }]" />
				<van-field v-model="legal_person_name" type="text" name="legal_person_name" label="法人名称："
					placeholder="请输入法人名称" :rules="[{ required: true, message: '请输入法人名称' }]" />
				<van-field v-model="shareholder" type="text" name="shareholder" label="股东名称：" placeholder="请输入股东名称"
					:rules="[{ required: true, message: '请输入股东名称' }]" />

				<van-field v-model="contact_number" type="tel" name="contact_number" label="联系电话：" placeholder="请输入联系电话"
					:rules="[{ required: true, message: '请输入联系电话' }]" />
				<!-- <van-field v-if="level == 0" v-model="contact_phone" type="tel" name="contact_phone" label="联系电话："
					placeholder="请输入联系电话" :rules="[{ required: true, message: '请输入联系电话' }]" /> -->
				<div>
					<div class="uploader">
						<div class="after-sales-title">请上传营业执照</div>
						<van-uploader v-model="voucher_urls" multiple :max-count="1" :after-read="afterRead"
							:before-delete="uploadDlete" />
						<div class="tips_up">上传营业执照</div>
					</div>
					<div class="uploader">
						<div class="after-sales-title">请上传公司门头照</div>
						<van-uploader v-model="front_images" multiple :max-count="4" :after-read="afterReadFront"
							:before-delete="uploadDleteFront" />
						<div class="tips_up">上传公司门头照</div>
					</div>
					<div class="uploader">
						<div class="after-sales-title">请上传公司内部展示照片</div>
						<van-uploader v-model="inside_images" multiple :max-count="4" :after-read="afterReadInside"
							:before-delete="uploadDleteInside" />
						<div class="tips_up">上传公司内部展示照片</div>
					</div>
					<div class="uploader">
						<div class="after-sales-title">请上传公司组织架构图</div>
						<van-uploader v-model="organization_chart" multiple :max-count="4"
							:after-read="afterReadOrganization" :before-delete="uploadDleteOrganization" />
						<div class="tips_up">上传公司组织架构图</div>
					</div>
				</div>
				<!-- <van-field name="voucher_urls" label="" :rules="[{ required: true, message: '请上传' }]" style="">
					<template #input>
						
					</template>
</van-field> -->
				<!-- <div class="apply_tips">
					<div class="apply_tips_title">温馨提示:</div>
					<div class="apply_tips_content">
						在提交申请后，会有平台的客服人员跟您联系，进行权益、门槛等相关的讲解。
					</div>
				</div> -->

				<div class="apply-btn">
					<van-button round block type="info" native-type="submit">提交申请</van-button>
				</div>
			</van-form>
			<!-- 省市区 -->
			<van-popup v-model="showPopup" position="bottom">
				<van-cascader v-model="cascaderValue" title="请选择地址" :options="options" @close="showPopup = false"
					@change="onChange" @finish="onFinish" active-color="#1D69E4" />
			</van-popup>
			<!-- 大区 -->
			<van-popup v-model="bigShowPopup" position="bottom">
				<van-picker title="选择代理区域" value-key="name" show-toolbar :columns="bigAgentConfig"
					@confirm="onConfirmBig" @cancel="bigShowPopup = false" :value="cascaderValue" />
			</van-popup>
			<!-- 选择区域 -->
			<van-popup v-model="showPopuplevel" position="bottom">
				<van-picker title="选择代理区域" value-key="name" show-toolbar :columns="levelAgentConfig"
					@confirm="onConfirmLevel" @cancel="showPopuplevel = false" :value="cascaderValueLevel" />
			</van-popup>
		</div>



	</div>
</template>
<script>
import {
	AGENT_REGION_LIST,
	AGENT_APPLY,
	BIG_AGENT_CONFIG,
	BIG_AGENT_APPLY,
	OCR_RECOGNIZE
} from "@/api/mine";
import { getOssParams, uploadImage, uploadDelete } from '@/api/upload';
export default {
	data() {
		return {
			level: "",
			region_code: "",
			region_name: "",
			name: "",
			contact_phone: "",
			showPopup: false,
			cascaderValue: "",
			options: [],
			bigAgentConfig: [],
			bigShowPopup: false,
			level_name: "",
			showPopuplevel: false,
			cascaderValueLevel: "",


			company_name: "",
			credit_code: "",
			legal_person_name: "",
			shareholder: "",
			contact_number: "",
			business_address: "",
			business_license: "",
			front_images: [],
			inside_images: [],
			organization_chart: [],

			levelAgentConfig: [
				{
					name: '省代理',
					id: 1
				},
				{
					name: '市代理',
					id: 2
				},
				{
					name: '区代理',
					id: 3
				},
				{
					name: '大区代理',
					id: 100
				}
			],
			// msg:null
			title: this.$route.query.name,
			voucher_urls: [],
		};
	},
	mounted() {
		window.scrollTo(0, 0);
		window.document.title = this.$route.query.name;
		// this.msg=this.$route.query.level?1:0
		// if (this.$route.query.level) {
		this.level_name = this.$route.query.level == 1 ?
			"省代理" : this.$route.query.level == 2 ? "市代理" : this.$route.query.level == 3 ? "区代理" : "大区代理";
		this.level = Number(this.$route.query.level)
		this.cascaderValueLevel = Number(this.$route.query.level)
		if (this.level == 0 || this.level == 100) {
			this.$http.get(BIG_AGENT_CONFIG).then((res) => {
				this.bigAgentConfig = res.data.map(item => ({
					...item,
					disabled: item.count >= 1 // 如果 count >= 1，则禁用该选项
				}));
			});
		} else {
			this.fetchRegions(1, 0);

		}
		// }
		// this.level_name =""
		// 	this.$route.query.level == 1 ?
		// 	"省代理" :
		// 	this.$route.query.level == 2 ?
		// 	"市代理" :
		// 	this.$route.query.level == 3 ?
		// 	"区代理" :
		// 	"大区代理";
		// this.level = this.$route.query.level
		// if (this.level != 0) {
		// 	this.fetchRegions(1, 0);
		// } else {
		// 	this.$http.get(BIG_AGENT_CONFIG).then((res) => {
		// 		this.bigAgentConfig = res.data.map(item => ({
		// 			...item,
		// 			disabled: item.count >= 1 // 如果 count >= 1，则禁用该选项
		// 		}));
		// 	});
		// }
	},
	methods: {
		async afterRead(file) {
			try {
				// 获取OSS上传参数
				if (!this.ossParams || this.ossParams.expire_time < Date.now()) {
					this.ossParams = await getOssParams(this.$http);
				}
				if (!this.ossParams) {
					throw new Error('OSS参数未正确设置');
				}
				// 调用封装的上传函数
				await uploadImage(file, this.ossParams, this.voucher_urls);
				// console.log(this.voucher_urls);
				let params={
					type: "business_license",
          			image_url: this.voucher_urls.map((item) => item.url)[0],
				}
				this.$http.post(OCR_RECOGNIZE, params).then((res) => {
					this.company_name = res.data.business_license.company_name
					this.credit_code = res.data.business_license.credit_code
					this.legal_person_name = res.data.business_license.legal_person
					this.business_address = res.data.business_license.business_address
				});

			} catch (error) {
				console.error('处理上传错误:', error);
			}
		},

		uploadDlete(file) {
			this.voucher_urls = uploadDelete(file, this.voucher_urls);
		},
		//门头
		async afterReadFront(file) {
			try {
				// 获取OSS上传参数
				if (!this.ossParams || this.ossParams.expire_time < Date.now()) {
					this.ossParams = await getOssParams(this.$http);
				}
				if (!this.ossParams) {
					throw new Error('OSS参数未正确设置');
				}
				// 调用封装的上传函数
				await uploadImage(file, this.ossParams, this.front_images);
				// console.log(this.front_images);

			} catch (error) {
				console.error('处理上传错误:', error);
			}
		},
		uploadDleteFront(file) {
			this.front_images = uploadDelete(file, this.front_images);
		},
		//内部
		async afterReadInside(file) {
			try {
				// 获取OSS上传参数
				if (!this.ossParams || this.ossParams.expire_time < Date.now()) {
					this.ossParams = await getOssParams(this.$http);
				}
				if (!this.ossParams) {
					throw new Error('OSS参数未正确设置');
				}
				// 调用封装的上传函数
				await uploadImage(file, this.ossParams, this.inside_images);

			} catch (error) {
				console.error('处理上传错误:', error);
			}
		},
		uploadDleteInside(file) {
			this.inside_images = uploadDelete(file, this.inside_images);
		},
		//架构
		async afterReadOrganization(file) {
			try {
				// 获取OSS上传参数
				if (!this.ossParams || this.ossParams.expire_time < Date.now()) {
					this.ossParams = await getOssParams(this.$http);
				}
				if (!this.ossParams) {
					throw new Error('OSS参数未正确设置');
				}
				// 调用封装的上传函数
				await uploadImage(file, this.ossParams, this.organization_chart);

			} catch (error) {
				console.error('处理上传错误:', error);
			}
		},
		uploadDleteOrganization(file) {
			this.organization_chart = uploadDelete(file, this.organization_chart);
		},
		onConfirmLevel(value) {
			this.level = value.id
			this.level_name = value.name
			this.options = []
			this.cascaderValue = ""
			this.region_name = ""
			// this.
			if (value.id != 100 || value.id != 100) {
				this.fetchRegions(1, 0);
			} else {
				this.$http.get(BIG_AGENT_CONFIG).then((res) => {
					this.bigAgentConfig = res.data.map(item => ({
						...item,
						disabled: item.count >= 1 // 如果 count >= 1，则禁用该选项
					}));
				});
			}
			this.showPopuplevel = false
			this.cascaderValueLevel = value.id
		},
		// 大区确定
		onConfirmBig(value) {
			// console.log(value);
			this.cascaderValue = value.id
			this.region_name = value.name
			this.bigShowPopup = false

		},
		// 选择器变化时的回调
		onChange(res) {
			this.tabIndex = res.tabIndex;
			//   console.log(res, "res");
			let index =
				this.level == 3 ? 2 : this.level == 2 ? 1 : 0;
			if (this.tabIndex === index) {
				// this.showPopup = false;
				return;
			}
			//点击加载下一级回调
			this.getSpaceListAgain(res.selectedOptions, res.value);
		},
		getSpaceListAgain(selectedOptions, value) {
			this.$http
				.get(AGENT_REGION_LIST, {
					params: {
						code: value,
					},
				})
				.then((res) => {
					const {
						data
					} = res;

					if (data && data.length) {
						this.setOptions(selectedOptions, data);
					}
				});
		},
		setOptions(selectedOptions, data) {
			let _options = this.options;
			selectedOptions.forEach((item, index) => {
				if (index) {
					//不是第一个则取下一级children
					_options = _options.children;
				}
				_options =
					_options[_options.findIndex((_item) => _item.value === item.value)];
			});
			//找到最后一级
			let index =
				this.level == 3 ? 1 : this.level == 2 ? 0 : 0;
			_options.children = data.map((item) => {
				return {
					text: item.name,
					value: item.code,
					children: this.tabIndex == index ? null : [],
				};
			});
		},
		// 确定省市区
		onFinish({
			selectedOptions
		}) {
			this.showPopup = false;

			this.selectAreaList = selectedOptions;

			selectedOptions = selectedOptions.filter((item) => {
				return item.value !== 0;
			});

			//   console.log(selectedOptions, "ll");

			this.region_name = selectedOptions.map((option) => option.text).join("/");
		},
		async fetchRegions(parentCode, level) {
			const res = await this.$http.get(AGENT_REGION_LIST, {
				params: {
					code: parentCode,
				},
			});
			const {
				data
			} = res;

			// 省级
			if (this.level == 1) {
				data.forEach((item) => {
					this.options.push({
						text: item.name,
						value: item.code,
						// children: [],
					});
				});
				return;
			} else {
				if (level === 0) {
					data.forEach((item) => {
						this.options.push({
							text: item.name,
							value: item.code,
							children: [],
						});
					});
				} else if (level === 1) {
					// 市级数据
					const province = this.options.find(
						(item) => item.value === parentCode
					);
					if (province) {
						province.children = data.map((item) => ({
							text: item.name,
							value: item.code,
							children: [],
						}));
					}
				} else if (level === 2) {
					// 区/县级数据
					this.options.forEach((province) => {
						const city = province.children.find(
							(item) => item.value === parentCode
						);
						if (city) {
							city.children = data.map((item) => ({
								text: item.name,
								value: item.code,
								children: [],
							}));
						}
					});
				}
			}

			//   else if (level === 3) {
			//     // 街道数据
			//     this.options.forEach((province) => {
			//       province.children.forEach((city) => {
			//         const county = city.children.find(
			//           (item) => item.value === parentCode
			//         );
			//         if (county) {
			//           county.children = data.map((item) => ({
			//             text: item.name,
			//             value: item.code,
			//           }));
			//         }
			//       });
			//     });
			//   }
		},
		onClickLeft() {
			this.$router.back();
		},
		// 提交申请
		onSubmit() {
			// if (this.level == 0) {
			// 	let params = {
			// 		level: this.level,
			// 		region_code: this.cascaderValue,
			// 		name: this.name,
			// 		contact_phone: this.contact_phone,
			// 	};
			// 	// 大区
			// 	this.$http.post(AGENT_APPLY, params).then((res) => {
			// 		this.$toast.success("申请成功");
			// 		this.$router.back();
			// 	});
			// } else {
			if (this.voucher_urls.length == 0) return this.$toast("请上传营业执照");
			if (this.front_images.length == 0) return this.$toast("请上传公司门头照");
			if (this.inside_images.length == 0) return this.$toast("请上传公司内部照片");
			if (this.organization_chart.length == 0) return this.$toast("请上传公司组织架构图");
			let data = {
				level: this.level,
				region_code:this.cascaderValue,
				company_name: this.company_name,
				credit_code: this.credit_code,
				legal_person_name: this.legal_person_name,
				shareholder: this.shareholder,
				contact_number: this.contact_number,
				business_address: this.business_address,
				business_license: this.voucher_urls[0].url,
				front_images: this.front_images.map(item => item.url),
				inside_images: this.inside_images.map(item => item.url),
				organization_chart: this.organization_chart.map(item => item.url)

			}
			this.$http.post(AGENT_APPLY, data).then((res) => {
				this.$toast.success("申请成功");
				this.$router.back();
			});
			// }
			// console.log(params);

		},
	},
};
</script>
<style lang="scss">
.mine-apply-agent-wrap {
	position: relative;
	// height: 100vh;
	padding-top: 46px;
	background-color: #fff;
	box-sizing: border-box;
	overflow: hidden;

	.uploader {
		width: 90%;
		margin: 0 auto;
		margin-top: .2rem;
		font-size: .28rem;

		.after-sales-title {
			margin-bottom: .2rem;
		}

		.tips_up {
			font-size: .24rem;
			color: #999;
		}
	}

	.van-nav-bar .van-icon {
		color: #333333;
	}

	.van-nav-bar__arrow {
		font-size: 20px;
	}

	.van-hairline--bottom::after {
		display: none;
	}

	.bg-img {
		display: block;
		width: 100%;
	}

	.form-wrap {
		// position: absolute;
		// top: 163px;
		// left: 0;
		// right: 0;
		// margin: auto;
		// width: 6.86rem;
		// height: 12.14rem;
		// border-radius: 0.16rem 0.16rem 0 0;
		// background-color: #ffffff;
		// overflow: hidden;
	}

	.van-cell {
		padding: 13px 17px;

		.van-field__label {
			width: 2.4rem;
		}
	}

	.apply_tips {
		width: 6.22rem;
		height: 1.76rem;
		padding: 0.28rem 0.2rem;
		margin: auto;
		margin-top: 0.36rem;
		border-radius: 0.08rem;
		box-sizing: border-box;
		background-color: #e9f0fb;

		.apply_tips_title {
			height: 0.4rem;
			margin-bottom: 0.12rem;
			line-height: 0.4rem;
			font-size: 0.28rem;
			font-weight: 500;
			color: #333333;
		}

		.apply_tips_content {
			line-height: 0.34rem;
			font-size: 0.24rem;
			color: #666666;
		}
	}

	.apply-btn {
		width: 6.06rem;
		height: 0.88rem;
		margin: auto;
		margin-top: 0.6rem;

		.van-button--info {
			border: none;
			background: linear-gradient(90deg, #4A89EC 0%, #1261E2 100%);
		}
	}
}
</style>
